<?php
require 'database.php';
$db = new DB();

$array = array('.', ':', ' ');

$Qry = 'SELECT id, tag, icon_url
		FROM cat
		WHERE icon IS NULL OR icon = ""
		LIMIT 20';

$res = $db->fetchAll($Qry);

foreach ($res as $key=>$value) {
	$condition = 'id = ' . $value['id'];
	$imgurl = $value['icon_url'];

	$file_parts = pathinfo($imgurl);
	$file_extension = $file_parts['extension'];

	$path = $_SERVER['DOCUMENT_ROOT'] . '/data/icon/';
	$new_file = $value['tag'];
	$new_file = $new_file . '.' . $file_extension;

	$image = getimg($imgurl);
	file_put_contents($path . $new_file, $image);

	$data = array(
			'icon'=>$new_file
	);

	$newIMG = $db->update('cat', $data, $condition);

	if ($newIMG)
		echo $key . ' <font color="green">- /data/icon/' .$new_file . ' ==> Add New</font><br />';
}

function getimg($url) {
	$headers[] = 'Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg';
	$headers[] = 'Connection: Keep-Alive';
	$headers[] = 'Content-type: application/x-www-form-urlencoded;charset=UTF-8';

	$user_agent = 'php';

	$process = curl_init($url);

	curl_setopt($process, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36');
	curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
	curl_setopt($process, CURLOPT_HEADER, 0);
	curl_setopt($process, CURLOPT_USERAGENT, $user_agent);
	curl_setopt($process, CURLOPT_TIMEOUT, 30);
	curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
	curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);

	$return = curl_exec($process);

	curl_close($process);

	return $return;
}